// pages/doctor-city-map/doctor-city-map.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: "",
    longitude: "",
    markers: [],
    cityList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCurrentPosition();
    this.getDoctorCityList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.mapCtx = wx.createMapContext('cityMap')
  },

  getCurrentPosition: function(){
    const t = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        t.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      }
    })
  },

  getDoctorCityList: function() {
    const t = this;
    app.request({
      url: 'doctor/city/getCityListForDoctor',
      data: {
        type:1 //医生
      },
      success: function (res) {
        const { data } = res;
        t.setData({
          cityList: data
        });
        t.getCoreCityList();
      },
      fail: function (res) {
        //app.requestFail(res);
      }
    });
  },

  getCoreCityList: function () {
    const t = this;
    app.request({
      url: 'doctor/city/getAreaListByCityCore',
      data: {
      },
      success: function (res) {
        const { data } = res;
        let cityList = t.data.cityList;
        cityList.forEach(function(city,index){
          let findeId = data.findIndex(function(item,idx){
            if(city.cityId ==item.areaId){
              return true
            }
          });
          if(findeId != -1){
            data.splice(findeId,1);
          }
        });
        cityList = cityList.concat(data);
        let markers = [];
        for (let i = 0; i < cityList.length; i++) {
          let item = cityList[i];
          markers.push({
            id: i,
            iconPath: "https://tyc-bj.cn/yc/api/attach/images/pos_icon.png",
            latitude: item.latitude,
            longitude: item.longitude,
            title: item.cityName||item.areaName,
            width: 25,
            height: 30
          });
        }
        t.setData({
          cityList: cityList,
          markers
        });
      },
      fail: function (res) {
        //app.requestFail(res);
      }
    });
  },

  markerTap:function(e){
    let findItem = this.data.markers.find(function(item){
      return item.id === e.markerId;
    })
    wx.navigateTo({
      url: `/pages/doctor-map/doctor-map?longitude=${findItem.longitude}&latitude=${findItem.latitude}`
    });
  }
})